import React, { PureComponent } from 'react';
import { formatMessage, FormattedMessage } from 'umi/locale';

import { connect } from 'dva';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Badge,
  Divider,
  Steps,
  Radio,
  Tabs,
  Table,
  Upload,
  List,
  Avatar,
  Checkbox,
  Tooltip,
} from 'antd';
import get from 'lodash/get';
import isEmpty from 'lodash/isEmpty';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import DescriptionList from '@/components/DescriptionList';
import StandardTable from '@/components/StandardTable';
import MyIcon from '@/components/MyIcon';
import IconButton from '@/components/IconButton';
import Headline from '@/components/Headline';
import ScrollSelect from '@/components/ScrollSelect';
import api from '@/api';
import styles from './AppConfig.less';
import router from 'umi/router';

const FormItem = Form.Item;
const InputGroup = Input.Group;
const Description = DescriptionList.Description;
const { TabPane } = Tabs;
const EXPIREDAYS = [
  {
    code: 60,
    name: '60天',
  },
  {
    code: 90,
    name: '90天',
  },
  {
    code: 180,
    name: '180天',
  },
  {
    code: 360,
    name: '360天',
  },
  {
    code: 0,
    name: '永久',
  },
];
let cardStyle = {
  bordered: false,
  headStyle: { border: 'none' },
  style: { width: '100%' },
};

@Form.create()
class EditFormModal extends PureComponent {
  constructor(props) {
    super(props);
  }

  handleOk = () => {
    const { form, onOk } = this.props;
    form.validateFields((err, values) => {
      if (err) {
        return;
      }
      onOk && onOk(values);
    });
  };

  render() {
    const { editVisible, onOk, onCancle } = this.props;
    const {
      form: { getFieldDecorator },
    } = this.props;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 },
      },
    };
    return (
      <Modal
        // confirmLoading={bindLoading}
        destroyOnClose={true}
        maskClosable={false}
        keyboard={false}
        title={formatMessage({ id: 'sysSet.FrontApp.AppConfig.editExpireDays' })}
        visible={editVisible}
        onOk={this.handleOk}
        onCancel={onCancle}
      >
        <Form layout="horizontal" className={styles.appConfig}>
          <FormItem label={formatMessage({ id: 'sysSet.FrontApp.AppConfig.expireDays' })}>
            {getFieldDecorator('expireDays', {
              rules: [
                {
                  required: true,
                  message: formatMessage({ id: 'sysSet.FrontApp.AppConfig.selectExpireDays' }),
                },
              ],
            })(
              <Select style={{ width: '100%' }}>
                {EXPIREDAYS.map(item => (
                  <Option value={item.code} key={item.code}>
                    {item.name}
                  </Option>
                ))}
              </Select>
            )}
          </FormItem>
        </Form>
      </Modal>
    );
  }
}

@Form.create()
@connect(({ loading, app }) => ({
  loading: loading.effects['app/queryBindList'],
  bindLoading: loading.effects['app/bindUser'],
  bindList: app.bindList,
}))
class Bind extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      type: 'create',
      visible: false,
      editVisible: false,
      selectedRowKeys: [],
      selectedRows: [],
    };
  }

  componentDidMount() {
    this.queryBindList();
  }

  columns = [
    {
      title: formatMessage({ id: 'sysSet.Common.index' }),
      render: (text, record, index) => {
        return <span>{this.calcIndex(index)}</span>;
      },
    },
    {
      title: formatMessage({ id: 'sysSet.Common.account' }),
      dataIndex: 'userName',
      render: (text, record, index) => {
        return (
          <span style={{ display: 'flex', alignItems: 'center' }}>
            {
              <Tooltip title={formatMessage({ id: 'sysSet.FrontApp.AppConfig.locked' })}>
                <MyIcon
                  type="iconoss---suoding"
                  style={{ fontSize: 28, visibility: record.isLocked ? 'visible' : 'hidden' }}
                />
              </Tooltip>
            }

            {record.isLocked ? (
              text
            ) : (
              <a
                onClick={() => {
                  this.goAppConfigPage(record);
                }}
              >
                {text}
              </a>
            )}
          </span>
        );
      },
    },
    {
      title: formatMessage({ id: 'sysSet.Common.code' }),
      dataIndex: 'userCode',
    },
    {
      title: 'appKey',
      dataIndex: 'appKey',
    },
    {
      title: 'appSecret',
      dataIndex: 'appSecret',
    },
    {
      title: formatMessage({ id: 'sysSet.FrontApp.AppConfig.createTime' }),
      dataIndex: 'createTime',
    },
    {
      title: formatMessage({ id: 'sysSet.FrontApp.AppConfig.expireDays' }),
      dataIndex: 'expireDate',
      render: (text, record, index) => {
        return <span>{record.expireDate || '--'}</span>;
      },
    },
  ];

  calcIndex = index => {
    const { bindList } = this.props;
    let currentPage = get(bindList, 'pagination.currentPage') || 1;
    let pageSize = get(bindList, 'pagination.pageSize') || 50;
    return (currentPage - 1) * pageSize + index + 1;
  };

  formatFieldsValue = fieldsValue => {
    let params = [];
    try {
      Object.keys(fieldsValue).forEach(key => {
        params.push({
          keyName: key,
          keyValue: fieldsValue[key],
        });
      });
    } catch (error) {}
    return params;
  };

  goAppConfigPage = record => {
    router.push({
      pathname: '/system/edi/frontApp/appConfig/appConfig',
      query: {
        appUserId: record.id,
        appId: this.props.location.query.appId,
      },
    });
  };

  queryBindList = ({ pageIndex = 1, pageSize = 50, ...params } = {}) => {
    const {
      dispatch,
      form,
      location: { query },
    } = this.props;
    let payload = {
      pageIndex: pageIndex,
      pageSize: pageSize,
      ...params,
    };
    dispatch({
      type: 'app/queryBindList',
      payload: {
        pathParams: {
          appId: query.appId,
        },
        queryParams: payload,
      },
    });
  };

  queryUserList = params => {
    const {
      dispatch,
      location: { query },
    } = this.props;
    return api.app.bind.user({
      queryParams: params,
    });
  };

  bindUser = params => {
    return this.props.dispatch({
      type: 'app/bindUser',
      payload: {
        data: params,
      },
    });
  };

  unbindUser = params => {
    return this.props.dispatch({
      type: 'app/unbindUser',
      payload: params,
    });
  };

  lockUser = params => {
    return this.props.dispatch({
      type: 'app/lockUser',
      payload: params,
    });
  };

  unlockUser = params => {
    return this.props.dispatch({
      type: 'app/unlockUser',
      payload: params,
    });
  };

  resetAppSecret = params => {
    return this.props.dispatch({
      type: 'app/resetUserSecret',
      payload: params,
    });
  };

  resetUserExpiredate = params => {
    return this.props.dispatch({
      type: 'app/resetUserExpiredate',
      payload: { data: params },
    });
  };

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const params = {
      pageIndex: pagination.current,
      pageSize: pagination.pageSize,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    this.queryBindList(params);
  };

  handleModalOnOk = () => {
    const { form, location } = this.props;
    form.validateFields(async (err, values) => {
      if (err) {
        return;
      }
      const params = {
        appId: location.query.appId,
        userId: values.userId.map(user => user.key),
        expireDays: values.expireDays,
      };
      const res = await this.bindUser(params);
      if (res.errorCode === 0) {
        message.success(formatMessage({ id: 'sysSet.Common.createSuccess' }));
        this.queryBindList();
        this.setState({
          visible: false,
        });
      }
    });
  };

  handleModalOnCancle = () => {
    this.setState({
      visible: false,
    });
  };

  handleEditModalOnOk = async values => {
    const { location } = this.props;
    const { selectedRows } = this.state;
    const params = {
      appId: location.query.appId,
      appKeys: selectedRows.map(row => row.appKey),
      expireDays: values.expireDays,
    };
    const res = await this.resetUserExpiredate(params);
    if (res.errorCode === 0) {
      message.success(formatMessage({ id: 'sysSet.Common.editSuccess' }));
      this.queryBindList();
      this.setState({
        editVisible: false,
      });
    }
  };

  handleEditModalOnCancle = () => {
    this.setState({
      editVisible: false,
    });
  };

  handleCreateClick = async () => {
    this.props.form.resetFields();
    this.setState({
      type: 'create',
      visible: true,
    });
  };

  handleEditClick = async () => {
    if (!this.state.selectedRowKeys || this.state.selectedRowKeys.length < 1) {
      return;
    }
    this.setState({
      type: 'edit',
      editVisible: true,
    });
  };

  handleUnbindClick = async () => {
    if (!this.state.selectedRowKeys || this.state.selectedRowKeys.length === 0) {
      return;
    }

    const {
      location: { query },
    } = this.props;

    Modal.confirm({
      title: formatMessage({ id: 'sysSet.Common.unbind' }),
      content: formatMessage({ id: 'sysSet.FrontApp.AppConfig.sureToUnbind' }),
      confirmLoading: true,
      onOk: async () => {
        const res = await this.unbindUser({
          pathParams: {
            appId: query.appId,
          },
          data: this.state.selectedRowKeys,
        });
        if (res.errorCode === 0) {
          this.setState({
            selectedRows: [],
            selectedRowKeys: [],
          });
          this.queryBindList();
          message.success(formatMessage({ id: 'sysSet.Common.actionSuccess' }));
        }
      },
    });
  };

  handleLockClick = async () => {
    if (!this.state.selectedRowKeys || this.state.selectedRowKeys.length === 0) {
      return;
    }

    const {
      location: { query },
    } = this.props;

    Modal.confirm({
      title: formatMessage({ id: 'sysSet.Common.lock' }),
      content: formatMessage({ id: 'sysSet.FrontApp.FrontApp.sureToLock' }),
      confirmLoading: true,
      onOk: async () => {
        const res = await this.lockUser({
          pathParams: {
            appId: query.appId,
          },
          data: this.state.selectedRowKeys,
        });
        if (res.errorCode === 0) {
          this.setState({
            selectedRows: [],
            selectedRowKeys: [],
          });
          this.queryBindList();
          message.success(formatMessage({ id: 'sysSet.Common.actionSuccess' }));
        }
      },
    });
  };

  handleUnlockClick = async () => {
    if (!this.state.selectedRowKeys || this.state.selectedRowKeys.length === 0) {
      return;
    }

    const {
      location: { query },
    } = this.props;

    Modal.confirm({
      title: formatMessage({ id: 'sysSet.Common.unlock' }),
      content: formatMessage({ id: 'sysSet.FrontApp.FrontApp.sureToUnlock' }),
      confirmLoading: true,
      onOk: async () => {
        const res = await this.unlockUser({
          pathParams: {
            appId: query.appId,
          },
          data: this.state.selectedRowKeys,
        });
        if (res.errorCode === 0) {
          this.setState({
            selectedRows: [],
            selectedRowKeys: [],
          });
          this.queryBindList();
          message.success(formatMessage({ id: 'sysSet.Common.actionSuccess' }));
        }
      },
    });
  };

  handleUnbindClick = async () => {
    if (!this.state.selectedRowKeys || this.state.selectedRowKeys.length === 0) {
      return;
    }

    const {
      location: { query },
    } = this.props;

    Modal.confirm({
      title: formatMessage({ id: 'sysSet.Common.unbind' }),
      content: formatMessage({ id: 'sysSet.FrontApp.AppConfig.sureToUnbind' }),
      confirmLoading: true,
      onOk: async () => {
        const res = await this.unbindUser({
          pathParams: {
            appId: query.appId,
          },
          data: this.state.selectedRowKeys,
        });
        if (res.errorCode === 0) {
          this.setState({
            selectedRows: [],
            selectedRowKeys: [],
          });
          this.queryBindList();
          message.success(formatMessage({ id: 'sysSet.Common.actionSuccess' }));
        }
      },
    });
  };

  handleResetClick = () => {
    if (this.state.selectedRowKeys.length !== 1) {
      return;
    }

    const {
      location: { query },
    } = this.props;

    Modal.confirm({
      title: formatMessage({ id: 'sysSet.FrontApp.AppConfig.resetSecret' }),
      content: formatMessage({ id: 'sysSet.FrontApp.AppConfig.sureToResetSecret' }),
      confirmLoading: true,
      onOk: async () => {
        const res = await this.resetAppSecret({
          pathParams: {
            appId: query.appId,
          },
          data: this.state.selectedRowKeys,
        });
        if (res.errorCode === 0) {
          this.queryBindList();
          this.setState({
            selectedRows: [],
            selectedRowKeys: [],
          });
          message.success(formatMessage({ id: 'sysSet.FrontApp.AppConfig.resetSuccess' }));
        }
      },
    });
  };

  handleSelectChange = (selectedRowKeys, selectedRows) => {
    this.setState({ selectedRowKeys, selectedRows });
  };

  renderEditModal = () => {
    const { editVisible } = this.state;
    const props = {
      editVisible: editVisible,
      onOk: this.handleEditModalOnOk,
      onCancle: this.handleEditModalOnCancle,
    };
    return <EditFormModal {...props} />;
  };

  renderModal = () => {
    const { visible } = this.state;
    const {
      bindLoading,
      form: { getFieldDecorator },
    } = this.props;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 },
      },
    };
    return (
      <Modal
        confirmLoading={bindLoading}
        maskClosable={false}
        keyboard={false}
        title={formatMessage({ id: 'sysSet.FrontApp.AppConfig.bindUser' })}
        visible={visible}
        onOk={this.handleModalOnOk}
        onCancel={this.handleModalOnCancle}
      >
        <Form layout="horizontal" className={styles.appConfig}>
          <FormItem label={<FormattedMessage id="sysSet.FrontApp.AppConfig.userNode" />}>
            {getFieldDecorator('userId', {
              rules: [
                {
                  required: true,
                  message: formatMessage({ id: 'sysSet.FrontApp.AppConfig.selectUser' }),
                },
              ],
            })(
              <ScrollSelect
                allowClear
                mode="multiple"
                search={this.queryUserList}
                optionKey="id"
                style={{ width: '100%' }}
              />
            )}
          </FormItem>
          <FormItem label={<FormattedMessage id="sysSet.FrontApp.AppConfig.expireDays" />}>
            {getFieldDecorator('expireDays', {
              rules: [
                {
                  required: true,
                  message: formatMessage({ id: 'sysSet.FrontApp.AppConfig.selectExpireDays' }),
                },
              ],
            })(
              <Select style={{ width: '100%' }}>
                {EXPIREDAYS.map(item => (
                  <Option value={item.code} key={item.code}>
                    {item.name}
                  </Option>
                ))}
              </Select>
            )}
          </FormItem>
        </Form>
      </Modal>
    );
  };

  renderTable = () => {
    const { loading, bindList } = this.props;
    const { selectedRowKeys } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.handleSelectChange,
    };
    return (
      <StandardTable
        showCheckbox
        selectedRows={selectedRowKeys}
        rowSelection={rowSelection}
        rowKey="appKey"
        loading={loading}
        data={bindList}
        columns={this.columns}
        onChange={this.handleStandardTableChange}
      />
    );
  };

  render() {
    return (
      <React.Fragment>
        <Headline
          style={{ marginBottom: 20 }}
          title={formatMessage({ id: 'sysSet.FrontApp.AppConfig.bindUser' })}
          backRoute={'/system/edi/frontApp'}
        />
        <Card {...cardStyle} className={styles.cargoApply}>
          <div style={{ marginBottom: 20, height: '30px' }}>
            {
              <div>
                <IconButton
                  title={formatMessage({ id: 'sysSet.Common.add' })}
                  icon="icon-add"
                  onClick={this.handleCreateClick}
                  style={{ marginRight: '12px' }}
                />
                <IconButton
                  title={formatMessage({ id: 'sysSet.Common.modify' })}
                  icon="icon-edit"
                  onClick={this.handleEditClick}
                  style={{ marginRight: '12px' }}
                />
                <IconButton
                  title={formatMessage({ id: 'sysSet.Common.unbind' })}
                  icon="iconoss---bangding"
                  onClick={this.handleUnbindClick}
                  style={{ marginRight: '12px' }}
                />
                <IconButton
                  title={formatMessage({ id: 'sysSet.Common.lock' })}
                  icon="iconoss---suoding"
                  onClick={this.handleLockClick}
                  style={{ marginRight: '12px' }}
                />
                <IconButton
                  title={formatMessage({ id: 'sysSet.Common.unlock' })}
                  icon="iconoss---jiesuo"
                  onClick={this.handleUnlockClick}
                  style={{ marginRight: '12px' }}
                />
                <IconButton
                  title={formatMessage({ id: 'sysSet.FrontApp.AppConfig.resetSecret' })}
                  icon="iconoss---zhongzhi"
                  onClick={this.handleResetClick}
                />
              </div>
            }
          </div>
          {this.renderTable()}
          {this.renderModal()}
          {this.renderEditModal()}
        </Card>
      </React.Fragment>
    );
  }
}

export default Bind;
